﻿#region License information
/*
 * Smart Include
 *  
 * Copyright (c) 2014 Fredrik Schultz
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * Project website: http://kaliko.com/smart-include/
 */
#endregion

namespace Kaliko.SmartInclude {
    using System.Collections.Generic;
    using System.IO;
    using System.IO.Compression;
    using System.Text.RegularExpressions;
    using System.Web;

    internal class CssMinifier {
        private static string _currentFile;

        /// <summary>
        /// Checks if the original files have been changed since the last compiled Css
        /// file was created. If they have been changed, all the files are collected and 
        /// minified into two files. One that is minified and one that's after being 
        /// minified also is compressed with GZip (which use less bandwidth but are 
        /// transparently uncompressed in most modern browsers).
        /// </summary>
        /// <param name="files"></param>
        /// <param name="media"></param>
        /// <returns></returns>
        internal static string MinifyCss(List<string> files, string media) {
            // Get a unique hash based on the requested files. This will 
            // be used for naming the combined scripts on the server.
            string hash = Common.GetStringHash(files);

            string filepath = Config.IncludeFilePath;
            string filename = hash + ".css";
            HttpServerUtility server = HttpContext.Current.Server;

            if(Common.HaveFilesBeenChanged(files, filename, filepath)) {
                MemoryStream stream = new MemoryStream();
                StreamWriter writer = new StreamWriter(stream);
                MatchEvaluator matchBackgroundImageUrl = FixImageUrl;
                Regex regex = new Regex("(?:url\\(\\s*(?:%s|[^)]*)\\s*\\))");

                // Combine and minify all Css files requested
                foreach(string file in files) {
                    if(File.Exists(server.MapPath(file))) {
                        FileStream infile = new FileStream(server.MapPath(file), FileMode.Open, FileAccess.Read, FileShare.Read);
                        string cssContent = new StreamReader(infile).ReadToEnd();
                        _currentFile = VirtualPathUtility.Combine(HttpContext.Current.Request.Path, file);

                        // Parse all image Urls
                        cssContent = regex.Replace(cssContent, matchBackgroundImageUrl);

                        writer.Write(Yahoo.Yui.Compressor.CssCompressor.Compress(cssContent));
                        writer.Flush();
                        infile.Close();
                    }
                }

                // Temporary fix to handle issue of missing last character in gzip stream
                writer.Write("    ");
                writer.Flush();

                // Save to  minified file
                FileStream outfile = new FileStream(filepath + filename, FileMode.Create, FileAccess.Write, FileShare.Write);
                stream.WriteTo(outfile);
                outfile.Close();

                // Save the minified file as a gzip archive
                outfile = new FileStream(filepath + filename + ".gz", FileMode.Create);
                GZipStream compressedzipStream = new GZipStream(outfile, CompressionMode.Compress, true);
                stream.WriteTo(compressedzipStream);

                compressedzipStream.Close();
                outfile.Close();

                writer.Close();
                stream.Close();
            }

            string datestamp = Common.GetFileDateHash(filepath + filename);

            return string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}Get.aspx?v={1}&d={2}&t=css\" media=\"{3}\" {4}>", Config.IncludePath, hash, datestamp, media, (Config.XhtmlMode ? " /" : ""));
        }



        /// <summary>
        /// Makes matched Url absolute.
        /// </summary>
        /// <param name="match"></param>
        /// <returns></returns>
        private static string FixImageUrl(Match match) {
            string url = match.ToString();
            url = url.Substring(4).Replace('\\', '/').Trim(new[] { '(', ')', '"', '\'' });

            // Check if URL is full or absolute
            if(url.Contains(":") || url.StartsWith("/")) {
                return "url(" + url + ")";
            }

            string newUrl = VirtualPathUtility.Combine(_currentFile, url);

            return "url(" + newUrl + ")";
        }
    }
}
